#include "json11/json11.hpp"
#include "TimeChecker.hpp"
#include <stdio.h>
#include <iostream>

using namespace json11;

std::string readFile(const char* filename) {
	FILE* file = fopen(filename, "rb");
	std::string str;
	if (file) {
		fseek(file, 0, SEEK_END);
		auto size = ftell(file);
		str.resize(size);
		fseek(file, 0, SEEK_SET);

		if (fread(&str[0], size, 1, file)) {
			
			return str;
		}else {
			return "";
		}
	}
	return str;
}


void testParse() {
	auto data = readFile("../data/citm_catalog.json");
	std::string error;
	TimeChecker checker;

	json11::Json::parse(data, error);

	printf("json11 cost %d\n", checker.elapsed());
}

void testParseNumber() {
	std::string error;
	std::string testjs = "{\"num\":1.234567890123,\"int\":1234567890123456}";
	auto rslt = json11::Json::parse(testjs, error);

	auto num = rslt["num"].get<double>();
	auto inte = rslt["int"].get<int64_t>();
	auto invalid = rslt["invalid"].get<int64_t>();

	std::cout << "parse number:" << num.value()
		<< " parse int:" << inte.value()
		<< " parse invalid:" << invalid.value_or(0) << std::endl;
}


void testFormat() {
	Json root;
	root.set("Name", Json("Zhangsan"));
	root.set("Age", Json(18));

	Json array;
	for (size_t i = 0; i < 10; ++i) {
		array.append(Json((int)i));
	}
	root.set("array", array);
	std::cout<<"json:"<< root.dump() << std::endl;
}


int main(int argc, const char* argv[]) {

	testParse();
	testParseNumber();
	testFormat();

	Json json;
	Json json2(json.array_items());
	json2.append(Json(123));

	auto items = json.array_items();

	getchar();
	return 0;
}

